<?php

/**
 * session.class.php
 *
 * @package adServer
 */
require_once ('./settings/siteConfig.php');
require_once (CLASS_PATH . 'classDatabase.php');
require_once (CLASS_PATH . 'dbStatements.php');
class adServerSession {
    public $username;
    public $password;
    public $firstRun = false;
    public $fullname;
    public $loggedIn = false;
    public $dbHandle;

    /**
     * Constructor
     */
    function adServerSession() {
        /* Create the DB connection */
        $this->dbHandle = new database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, false);

        /* Try to select the database */
        if ($this->dbHandle->selectDb(DB_NAME) != true) {
            /* DB is not setup, need to be setup */
            $this->setupDatabase();
        }
        if($this->loggedIn != true && $this->testDatabaseTables(DB_NAME)==false){
            $this->setupTables();  
            $this->firstRun = true;         
        }

        
        /* Check if already logged in */
        if (isset($_COOKIE["adServerManUser"]) && isset($_COOKIE["adServerNonce"]) &&
            $_COOKIE["adServerNonce"] == 'Ju5T4B451c4uth') {
            $this->username = $_COOKIE["adServerManUser"];
            $this->fullname = $_COOKIE["adServerManUserFull"];
            $this->loggedIn = true;
        }
    }

    /**
     * Start a session
     * 
     * @param String $username
     * @param String $fullname
     * @return 
     */
    function startSession($username, $fullname) {
        $expire = time() + 60 * 60 * 2; //expire in 2 hours
        setcookie("adServerManUser", $username, $expire);
        setcookie("adServerManUserFull", $fullname, $expire);
        setcookie("adServerNonce", 'Ju5T4B451c4uth', $expire);
    }

    /**
     * Close a session
     * 
     * @return 
     */
    function closeSession() {
        $expire = time() - 60; //expire in the past
        setcookie("adServerManUser", '', $expire);
        setcookie("adServerManUserFull", '', $expire);
        setcookie("adServerNonce", '', $expire);
        $this->username = '';
        $this->password = '';
        $this->loggedIn = false;
    }

    /**
     * Login User
     * 
     * @param String $user
     * @param String $password
     * @return 
     */
    function userLogin($user, $password) {
        $user = mysql_real_escape_string($user);
        $password = mysql_real_escape_string($password);
        $qry = str_replace('%%PASSWORD%%', md5($password), SQL_USER_LOGIN);
        $qry = str_replace('%%USER%%', $user, $qry);
        if ($this->dbHandle->get_result_bool($qry) == true) {
            $this->username = $user;
            $this->password = $password;
            $this->startSession($user, $password);
            return true;
        }
        return false;

    }

    /**
     * Create user account
     * 
     * @param String $user
     * @param String $password
     * @return 
     */
    function createAccount($user, $password) {
        $user = mysql_real_escape_string($user);
        $password = mysql_real_escape_string($password);
        $qry = str_replace('%%PASSWORD%%', md5($password), SQL_CREATE_USER);
        $qry = str_replace('%%USER%%', $user, $qry);
        return $this->dbHandle->qry($qry);
    }

    /**
     * Create advertisement unit in the DB
     * 
     * @param Integer $type
     * @param String $campaign
     * @param Integer $duration
     * @param Integer $offset
     * @param String $html
     * @param String $language
     * @return 
     */
    function createAdUnit($type, $campaign, $duration, $offset, $html, $language) {
        $type = mysql_real_escape_string($type);
        $campaign = mysql_real_escape_string($campaign);
        $duration = mysql_real_escape_string($duration);
        $offset = mysql_real_escape_string($offset);
        $html = mysql_real_escape_string($html);
        $language = mysql_real_escape_string($language);

        $qry = str_replace('%%TYPEID%%', $type, SQL_CREATE_ADUNIT);
        $qry = str_replace('%%DURATION%%', $duration, $qry);
        $qry = str_replace('%%OFFSET%%', $offset, $qry);
        $qry = str_replace('%%HTML%%', $html, $qry);
        $qry = str_replace('%%CAMPAIGN%%', $campaign, $qry);
        $qry = str_replace('%%LANGUAGE%%', $language, $qry);
        return $this->dbHandle->qry($qry);
    }

    /**
     * Update an existing adUnit
     * 
     * @param Integer $adUnitId
     * @param Integer $type
     * @param String $campaign
     * @param Integer $duration
     * @param Integer $offset
     * @param String $html
     * @param String $language
     * @return 
     */
    function updateAdUnit($adUnitId, $type, $campaign, $duration, $offset, $html,
        $language) {
        $adUnitId = mysql_real_escape_string($adUnitId);
        $type = mysql_real_escape_string($type);
        $campaign = mysql_real_escape_string($campaign);
        $duration = mysql_real_escape_string($duration);
        $offset = mysql_real_escape_string($offset);
        $html = mysql_real_escape_string($html);
        $language = mysql_real_escape_string($language);

        $qry = str_replace('%%TYPEID%%', $type, SQL_UPDATE_AD);
        $qry = str_replace('%%DURATION%%', $duration, $qry);
        $qry = str_replace('%%OFFSET%%', $offset, $qry);
        $qry = str_replace('%%HTML%%', $html, $qry);
        $qry = str_replace('%%CAMPAIGN%%', $campaign, $qry);
        $qry = str_replace('%%LANGUAGE%%', $language, $qry);
        $qry = str_replace('%%ADUNITID%%', $adUnitId, $qry);
        return $this->dbHandle->qry($qry);
    }

    /**
     * Delete exixting ad unit
     * 
     * @param Integer $adUnitId
     * @return 
     */
    function deleteAdUnit($adUnitId) {
        $adUnitId = mysql_real_escape_string($adUnitId);
        $qry = str_replace('%%ADUNITID%%', $adUnitId, SQL_DELETE_AD);
        return $this->dbHandle->qry($qry);
    }

    /**
     * Return details of a given adUnit
     * 
     * @param Integer $adUnitId
     * @return 
     */
    function getAdDetails($adUnitId) {
        $adUnitId = mysql_real_escape_string($adUnitId);        
        $qry = str_replace('%%ADUNITID%%', $adUnitId, SQL_GET_AD_DETAILS);
        return $this->dbHandle->get_results($qry);
    }

    /**
     * Return all adUnits
     * 
     * @return 
     */
    function getAdUnits() {
        return $this->dbHandle->get_results(SQL_GET_ADUNITS);
    }

    /**
     * Create and select the database doesnt exists
     * 
     * @return 
     */
    function setupDatabase() {
        $qry = str_replace('%%DBNAME%%', DB_NAME, SQL_CREATE_DATABASE);
        $this->dbHandle->qry($qry);
        $this->dbHandle->selectDb(DB_NAME);
    }
    
    /**
     * Create and initialise all tables if they dont exists
     * 
     * @return 
     */    
     function setupTables() {       
        $this->dbHandle->qry(SQL_CREATE_COLLECTION_TABLE);
        $this->dbHandle->qry(SQL_CREATE_ADKEYWORD_TABLE);
        $this->dbHandle->qry(SQL_CREATE_LOG_TABLE);
        $this->dbHandle->qry(SQL_CREATE_KEYWORD_TABLE);
        $this->dbHandle->qry(SQL_CREATE_USERS_TABLE);
        $this->dbHandle->qry(SQL_CREATE_CAMPAIGNS_TABLE);

        $query = explode(';', SQL_CREATE_LANGUAGE_TABLE);
        // Run the queries
        foreach ($query as $index => $sql) {
            if (strlen($sql) > 5)
                $this->dbHandle->qry($sql);
        }

        $query = explode(';', SQL_CREATE_TYPE_TABLE);
        // Run the queries
        foreach ($query as $index => $sql) {
            if (strlen($sql) > 5)
                $this->dbHandle->qry($sql);
        }

        $qry = str_replace('%%CAMPAIGN%%', 'Default', SQL_CREATE_CAMPAIGNS_ENTRY);
        $qry = str_replace('%%DESCRIPTION%%', 'Used when no campaign is defined',
            $qry);
        $this->dbHandle->qry($qry);

        $this->password = $this->generateTempPassword();
        $qry = str_replace('%%PASSWORD%%', md5($this->password), SQL_CREATE_USER);
        $qry = str_replace('%%USER%%', 'tmpAdmin', $qry);
        $this->username = 'tmpAdmin';
        $this->dbHandle->qry($qry);
        $this->startSession($this->username, $this->username);
        $this->loggedIn = true;
    }


    function testDatabaseTables($dbName){
        $tableToTest=array('ad_collection','ad_log','users','ad_campaigns','ad_type','languages');
        $success=true;
        foreach($tableToTest as $table){
           if($this->dbHandle->table_exists($table)==false) $success=false; 
        }
        return $success;        
    }
    
    /**
     * Return randomly generated password
     * @return 
     */
    function generateTempPassword() {
        $vowels = 'aeuyAEUY23456789@#$%';
        $consonants = 'bdghjmnpqrstvzBDGHJLMNPQRSTVWXZ';
        $password = '';
        $alt = time() % 2;
        for ($i = 0; $i < 8; $i++) {
            if ($alt == 1) {
                $password .= $consonants[(rand() % strlen($consonants))];
                $alt = 0;
            } else {
                $password .= $vowels[(rand() % strlen($vowels))];
                $alt = 1;
            }
        }
        return $password;
    }

}

?>